<?php
/**
 * Created by PhpStorm.
 * User: another
 * Date: 2019-04-23
 * Time: 16:47
 */
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Permission;
use Illuminate\Http\Request;

class PermissionsController extends Controller
{
    protected $permissionModel;

    public function __construct()
    {
        $this->permissionModel = new Permission();
    }

    public function addPermission(Request $request)
    {
        $data = $request->input();
        $bool_data = $this->getValidator($data);

        if($bool_data['code'] == 0){
            $result['code'] = '0';
            $result['message'] = $bool_data['message'];
            return response()->json($result);
        }

        $bool = $this->permissionModel->addPermission($data);
        return response()->json($bool);
    }

    public function updPermission(Request $request)
    {
        $data = $request->input();
        $bool_data = $this->getValidator($data);

        if($bool_data['code'] == 0){
            $result['code'] = '0';
            $result['message'] = $bool_data['message'];
            return response()->json($result);
        }

        $bool = $this->permissionModel->updPermission($data);
        return response()->json($bool);
    }

    /**
     * 验证
     * @param $data
     * @return array
     */
    public function getValidator($data)
    {
        $validator = \Validator::make($data,[
            'pid'=>'required|integer',
            'name'=>'required|max:50',
            'display_name'=>'required',
            'description'=>'required',
        ],[
            'required'=>':attribute为必填项',
            'max'=>':attribute长度不符合要求',
            'integer'=>':attribute必须为数字',
        ],[
            'pid'=>'权限所属',
            'name'=>'权限规则',
            'display_name'=>'权限名称',
            'description'=>'权限描述',
        ]);


        //验证失败，并返回第一个报错
        if($validator->fails()) {
            return ['code' => 0, 'message' => $validator->errors()->first()];
        }

        return ['code'=>1,'message'=>'验证成功'];
    }
}